import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sainbainu/common/values/colors.dart';

import 'index.dart';

class LanguagePage extends GetView<LanguageController> {
  const LanguagePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GetBuilder<LanguageController>(
      builder: (_) {
        return Scaffold(
          appBar: AppBar(
            leading: _buildCancelBtn(),
            leadingWidth: 70,
            title: Text("设置语言".tr),
            actions: [
              _buildCompleteBtn(),
              const SizedBox(width: 15),
            ],
          ),
          body: _buildView(),
        );
      },
    );
  }

  Widget _buildCancelBtn() {
    return TextButton(
      onPressed: () => Get.back(),
      style: TextButton.styleFrom(
        foregroundColor: AppColors.active,
        textStyle: const TextStyle(fontSize: 16),
        padding: const EdgeInsets.all(0),
      ),
      child: Text("取消".tr),
    );
  }

  Widget _buildCompleteBtn() {
    return SizedBox(
      height: 34,
      child: ElevatedButton(
        onPressed: controller.state.selectedLocale == null
            ? null
            : controller.onChangeLanguage,
        style: ElevatedButton.styleFrom(
          backgroundColor: AppColors.danger,
          foregroundColor: Colors.white,
          padding: const EdgeInsets.all(0),
        ),
        child: Text("完成".tr),
      ),
    );
  }

  // 主视图
  Widget _buildView() {
    List<Widget> langWidgetlist = [];
    List<Language> languageList = controller.state.languageList;

    for (var i = 0; i < languageList.length; i++) {
      var e = languageList[i];
      langWidgetlist.add(_buildCellItem(
        title: e.title,
        isSelected: controller.checkSelected(e.locale),
        onTap: () {
          controller.onSelectLanguage(e.locale);
        },
      ));
      langWidgetlist.addIf(i < languageList.length - 1, _buildDivider());
    }

    return SingleChildScrollView(
      physics: const BouncingScrollPhysics(),
      child: Column(
        children: langWidgetlist,
      ),
    );
  }

  /// 分割线
  Widget _buildDivider() {
    return const Divider(
      height: 0,
      indent: 16,
      endIndent: 16,
      thickness: 0.5,
      color: AppColors.border,
    );
  }

  // 菜单每一项
  Widget _buildCellItem({
    required String title,
    bool isSelected = false,
    void Function()? onTap,
  }) {
    return ListTile(
      title: Text(title),
      trailing: isSelected ? const Icon(Icons.check_rounded) : null,
      tileColor: Colors.white,
      enableFeedback: true,
      contentPadding: const EdgeInsets.symmetric(horizontal: 16),
      selected: isSelected,
      selectedColor: AppColors.danger,
      selectedTileColor: Colors.white,
      onTap: onTap,
    );
  }
}
